/**
 * Created by wust on 2019-11-01 10:20:05
 * Copyright © 2019 wust. All rights reserved.
 */
package com.sc.admin.core.api.open;


import cn.hutool.core.lang.Validator;
import com.sc.common.annotations.OpenApi;
import com.sc.common.annotations.OperationLog;
import com.sc.common.dto.ApiResponseDto;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.enums.OperationLogEnum;
import com.sc.common.enums.RedisKeyEnum;
import com.sc.common.enums.ReturnCode;
import com.sc.common.util.GenVerificationCodeUtil;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.cache.SpringRedisTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * @author: wust
 * @date: Created in 2019-11-01 10:20:05
 * @description: 获取验证码开放接口
 *
 */
@Api(tags = {"开放接口~获取验证码"})
@OpenApi
@RequestMapping("/api/open/v1/VerificationCodeOpenApi")
@RestController
public class VerificationCodeOpenApi {
    static Logger logger = LogManager.getLogger(VerificationCodeOpenApi.class);

    @Autowired
    private SpringRedisTools springRedisTools;

    @Autowired
    private Environment env;

    /**
     *
     * @param loginName  登录账号：手机号码或者邮箱
     * @param type  验证码类型：1注册、2App登录、3找回密码、4web登陆
     * @return
     */
    @ApiOperation(value = "获取验证码", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name="loginName",value="登陆账号",required=true,paramType="query"),
            @ApiImplicitParam(name="type",value="验证码类型：1注册、2App登录、3找回密码、4web登陆",required=true,paramType="query")
    })
    @OperationLog(moduleName= OperationLogEnum.MODULE_COMMON,businessName="端获取验证码",operationType= OperationLogEnum.Search)
    @RequestMapping(value = "",method = RequestMethod.GET,produces ="application/json;charset=utf-8")
    public @ResponseBody
    ApiResponseDto getVerificationCode(@RequestParam String loginName, @RequestParam String type) {

        WebResponseDto responseDto = new WebResponseDto();
        if(MyStringUtils.isBlank(loginName)){
            return ApiResponseDto.failure(ReturnCode.INVALID_PARAMETERS_NULL);
        }

        if(!Validator.isEmail(MyStringUtils.null2String(loginName)) && !Validator.isMobile(MyStringUtils.null2String(loginName))){
            return ApiResponseDto.failure(ReturnCode.INVALID_PARAMETERS_ILLEGAL);
        }


        String verificationCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        String key = String.format(RedisKeyEnum.REDIS_KEY_STRING_VERIFICATION_CODE.getStringValue(),type,loginName,verificationCode);
        springRedisTools.addData(key,null,10, TimeUnit.MINUTES);

        try {
            if (Validator.isEmail(MyStringUtils.null2String(loginName))){
                String hostName = env.getProperty("app.verification-code.email.host-name");
                String fromUserName = env.getProperty("app.verification-code.email.from-user-name");
                String fromUserPwd = env.getProperty("app.verification-code.email.from-user-pwd");
                String subject = env.getProperty("app.verification-code.email.subject");
                String messageTemplate = env.getProperty("app.verification-code.email.message-template");

                String msg = String.format(messageTemplate,loginName,verificationCode);
                GenVerificationCodeUtil.sendMail(hostName,fromUserName,fromUserPwd,loginName,subject,msg);

                if(logger.isInfoEnabled()){
                    if("1".equals(type)){
                        logger.info("app账号注册获取验证码：" + msg);
                    }else if("2".equals(type)){
                        logger.info("app登录获取验证码：" + msg);
                    }else if("3".equals(type)){
                        logger.info("app找回密码获取验证码：" + msg);
                    }else if("4".equals(type)){
                        logger.info("web短信验证码登录获取验证码：" + msg);
                    }
                }
            }


            if(Validator.isMobile(MyStringUtils.null2String(loginName))){
                if(loginName.length() != 11){
                    return ApiResponseDto.failure(ReturnCode.INVALID_PARAMETERS_ILLEGAL);
                }

                String url = env.getProperty("app.verification-code.msg.url");
                String account = env.getProperty("app.verification-code.msg.account");
                String pwd = env.getProperty("app.verification-code.msg.pwd");
                String messageTemplate = env.getProperty("app.verification-code.msg.message-template");

                String msg = String.format(messageTemplate,loginName,verificationCode);
                GenVerificationCodeUtil.sendMsg(url,account,pwd,loginName,msg);

                if(logger.isInfoEnabled()){
                    if("1".equals(type)){
                        logger.info("app账号注册获取验证码：" + msg);
                    }else if("2".equals(type)){
                        logger.info("app登录获取验证码：" + msg);
                    }else if("3".equals(type)){
                        logger.info("app找回密码获取验证码：" + msg);
                    }else if("4".equals(type)){
                        logger.info("web短信验证码登录获取验证码：" + msg);
                    }
                }
            }
        } catch (Exception e) {
            return ApiResponseDto.failure(ReturnCode.INVALID_PARAMETERS_ILLEGAL,e.getMessage());
        }
        return ApiResponseDto.failure(ReturnCode.SUCCESS);
    }
}
